/**
 * 作者：Sky
 * QQ：2780619724
 * 此为main函数
 * 集成了各种设置操作
 */

import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class Q_GMS_Environment_SetUp {

    public static  void main(String[] args){
        AndroidDriver<WebElement> driver = null;
        List<String> SNList = new ArrayList<String>();
        WebElement element = null;


        //定义一个 Process用作执行adb命令
        Process process = null;

        System.out.println("#######################################################");
        System.out.println("作者：Sky");
        System.out.println("QQ：2780619724");
        System.out.println("该脚本仅用于安卓10.0系统GMS手机端环境设置");
        System.out.println("脚本版本日期：20201219");
        System.out.println("#######################################################");
        System.out.println("");

        //1、获取到手机SN号
        GetSNList getSNList = new GetSNList();
        SNList = getSNList.getSNList();
        String SN = SNList.get(0);

        //如果SN为空即手机没有连上adb,等待5秒钟，供手动点击OK按钮；
        if(SN.equals("")){
            System.out.println("手机序列号为： "+SN);
            System.out.println("手机没有连上电脑的adb，等待8秒钟，请手动勾选并点击OK按钮，确保手机连接上电脑。");
            try {
                Thread.sleep(8000);
                SNList = getSNList.getSNList();
                SN = SNList.get(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("手机序列号为： "+SN);



        //2、构建DesiredCapabilities，创建driver。
        DesiredCapabilities cap=new DesiredCapabilities();
        cap.setCapability("automationName", "Appium");
        cap.setCapability("deviceName", SN);
        cap.setCapability("platformName", "Android");
        cap.setCapability("appPackage","com.android.settings");
        cap.setCapability("appActivity","com.android.settings.Settings");

        System.out.println("开始创建appium driver");
        try{
            driver = new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"),cap);
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("创建appium driver结束");


        //定义一个显示等待的WebDriverWait
        WebDriverWait explicitwait = new WebDriverWait(driver, 10);


        System.out.println();
        System.out.println("#########10.0系统，GMS测试,手机端设置环境开始###########");
        System.out.println();


        //1、进入Network & internet，打开WiFi开关，并连接翻墙网络；
        System.out.println("1、开始设置：连接翻墙网络");

        //显示等待 Network & internet
        try {
            element = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//android.widget.TextView[@text='Network & internet']")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        element.click();//点击进入Network & internet


        //显示等待 wifi 开关按钮
        try {
            element = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.id("com.android.settings:id/switchWidget")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String Wifi_staute_ = element.getText();//获取wifi开关状态

        if(Wifi_staute_.equals("OFF")) {
            driver.findElementById("com.android.settings:id/switchWidget").click();//如果WiFi为off，则点击打开开关；
            driver.findElementByXPath("//android.widget.TextView[@text='Wi‑Fi']").click();//点击进入wifi热点列表

            //等待8秒钟，供GMSTEST网络在列表里面显示，此等待主要是为debug版本考虑
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //显示等待翻墙网络GMSTEST热点
            try {
                element = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//android.widget.TextView[@text='GMSTEST']")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            element.click();//点击进入翻墙网络GMSTEST热点


            //显示等待翻墙网络GMSTEST热点的输入框
            try {
                element = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.id("com.android.settings:id/password")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            element.sendKeys("qwertyuiop");//输入翻墙网络密码


            //显示等待CONNECT按钮出现
            try {
                element = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//android.widget.Button[@text='CONNECT']")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            element.click();//点击连接
        }

            //1b、如果wifi开关为ON
            if(Wifi_staute_.equals("ON")){
                driver.findElementByXPath("//android.widget.TextView[@text='Wi‑Fi']").click();//点击进入wifi热点列表
                //显示等待翻墙网络热点
                try {
                    element  = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//android.widget.TextView[@text='GMSTEST']")));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                element.click();//点击进入翻墙网络热点


                //显示等待翻墙网络GMSTEST热点的输入框
                try {
                    element = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.id("com.android.settings:id/password")));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                element.sendKeys("qwertyuiop");//输入翻墙网络密码


                //显示等待CONNECT按钮出现
                try {
                    element  = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//android.widget.Button[@text='CONNECT']")));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                element.click();//点击连接
            }
            System.out.println("1、结束设置：连接翻墙网络");
            System.out.println();


            //等待15秒钟，供连接wifi通知自动消失
            try {
                Thread.sleep(15000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            //按2次back键返回到settings界面
            try {
                process = Runtime.getRuntime().exec("adb shell input keyevent 4");
                process.waitFor();
                process = Runtime.getRuntime().exec("adb shell input keyevent 4");
                process.waitFor();
            } catch (IOException e) {
                e.printStackTrace();
            }catch(InterruptedException ie){
                ie.printStackTrace();
            }


            //2、打开gps

            //向上滑动直到屏幕出现Location元素并且可以点击
            SwipeFindElement sfe = new SwipeFindElement(driver);
            sfe.swipeUpFindElement(By.xpath("//android.widget.TextView[@text='Location']"));

            System.out.println("2、开始设置：打开GPS");
            driver.findElementByXPath(("//android.widget.TextView[@text='Location']")).click();//点击Location并进入

            //显示等待 Use location 开关按钮
            try {
                element = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.id("com.android.settings:id/switch_widget")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            String use_location_staute = element.getText();//获取 Use location 的状态

            //如果location状态为OFF则打开，如果为ON则不执行 ；然后返回上一级界面
            if(use_location_staute.equals("OFF")){
                driver.findElementById("com.android.settings:id/switch_widget").click();
            }
            //按back键返回到settings界面
            try {
                Runtime.getRuntime().exec("adb shell input keyevent 4").waitFor();
            } catch (IOException e) {
                e.printStackTrace();
            } catch(InterruptedException ie){
                ie.printStackTrace();
            }
            System.out.println("2、结束设置：打开GPS");
            System.out.println();



            //3、设置锁屏方式为None

        //向上滑动直到屏幕出现Security元素并且可以点击
        sfe = new SwipeFindElement(driver);
        sfe.swipeUpFindElement(By.xpath("//android.widget.TextView[@text='Security']"));

        System.out.println("3、开始设置：锁屏方式选择None");
        driver.findElementByXPath(("//android.widget.TextView[@text='Security']")).click();//点击Security并进入


        //向上滑动直到屏幕出现Screen lock元素并且可以点击
        sfe = new SwipeFindElement(driver);
        sfe.swipeUpFindElement(By.xpath("//android.widget.TextView[@text='Screen lock']"));
        //判断Screen lock 是否为None，如果为None直接返回,否则进入操作
        String screen_lock_statue = driver.findElementByXPath(("//android.widget.TextView[@text='Screen lock']/following-sibling::android.widget.TextView")).getText();
        //System.out.println(screen_lock_statue);
        if(screen_lock_statue.equals("None")){

            //按back键返回到settings界面
            try {
                Runtime.getRuntime().exec("adb shell input keyevent 4").waitFor();
            } catch (IOException e) {
                e.printStackTrace();
            }
            catch(InterruptedException ie){
                ie.printStackTrace();
            }
        }else{
            driver.findElementByXPath(("//android.widget.TextView[@text='Screen lock']")).click();//点击Screen lock并进入
            driver.findElementByXPath("//android.widget.TextView[@text='None']").click();//点击None，设置None锁屏方式
            //按back键返回到settings界面
            try {
                Runtime.getRuntime().exec("adb shell input keyevent 4").waitFor();
            } catch (IOException e) {
                e.printStackTrace();
            }
            catch(InterruptedException ie){
                ie.printStackTrace();
            }

        }

        System.out.println("3、结束设置：锁屏方式选择None");
        System.out.println();




        //4、进入Account 关闭Automatically sync data
        //向上滑动直到屏幕出现Account元素并且可以点击
        sfe = new SwipeFindElement(driver);
        sfe.swipeUpFindElement(By.xpath("//android.widget.TextView[@text='Accounts']"));

        System.out.println("4、开始设置：关闭Automatically sync data");
        driver.findElementByXPath(("//android.widget.TextView[@text='Accounts']")).click();//点击Accounts并进入


        //显示等待 sync_data_statue 开关按钮
        try {
            element = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.id("android:id/switch_widget")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String sync_data_statue = element.getText();//获取Automatically sync data开关状态

        //如果为ON，则关闭；如果为OFF不操作，然后返回到上一级界面
        if(sync_data_statue.equals("ON")){
            driver.findElementById("android:id/switch_widget").click();
            driver.findElementById("android:id/button1").click();
        }
        System.out.println("4、结束设置：关闭Automatically sync data");
        System.out.println();


        //按back键返回到settings界面
        try {
            Runtime.getRuntime().exec("adb shell input keyevent 4").waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch(InterruptedException ie){
            ie.printStackTrace();
        }



        //5、关闭Automatic time zone 和 Use locale default 开关
        //向上滑动直到屏幕出现System元素并且可以点击
        sfe = new SwipeFindElement(driver);
        sfe.swipeUpFindElement(By.xpath("//android.widget.TextView[@text='System']"));

        System.out.println("5、开始设置：关闭Use 24-hour format 开关。");
        driver.findElementByXPath(("//android.widget.TextView[@text='System']")).click();//点击System并进入
        driver.findElementByXPath("//android.widget.TextView[@text='Date & time']").click();//点击Date & time并进入


        /**
        String automatic_time_zone = driver.findElementByXPath("//android.widget.TextView[@text='Automatic time zone']/parent::android.widget.RelativeLayout/following-sibling::android.widget.LinearLayout/android.widget.Switch").getText();
        if(automatic_time_zone.equals("ON")){
            driver.findElementByXPath("//android.widget.TextView[@text='Automatic time zone']/parent::android.widget.RelativeLayout/following-sibling::android.widget.LinearLayout/android.widget.Switch").click();
        }


        //向上滑动直到屏幕出现Use_locale_default元素
        sfe = new SwipeFindElement(driver);
        sfe.swipeUpFindElement(By.xpath("//android.widget.TextView[@text='Use locale default']"));

        String Use_locale_default = driver.findElementByXPath("//android.widget.TextView[@text='Use locale default']/parent::android.widget.RelativeLayout/following-sibling::android.widget.LinearLayout/android.widget.Switch").getText();
        if(Use_locale_default.equals("ON")){
            driver.findElementByXPath("//android.widget.TextView[@text='Use locale default']/parent::android.widget.RelativeLayout/following-sibling::android.widget.LinearLayout/android.widget.Switch").click();
        }

        **/


        //用while循环向上滑动直到屏幕出现Use 24-hour format元素
        sfe = new SwipeFindElement(driver);
        sfe.swipeUpFindElement(By.xpath("//android.widget.TextView[@text='Use 24-hour format']"));

        String use_24_hour_format = driver.findElementByXPath("//android.widget.TextView[@text='Use 24-hour format']/parent::android.widget.RelativeLayout/following-sibling::android.widget.LinearLayout/android.widget.Switch").getText();
        if(use_24_hour_format.equals("ON")){
            driver.findElementByXPath("//android.widget.TextView[@text='Use 24-hour format']/parent::android.widget.RelativeLayout/following-sibling::android.widget.LinearLayout/android.widget.Switch").click();
        }

        System.out.println("5、结束设置：关闭Use 24-hour format 开关。");
        System.out.println();



        //按1次back键返回到System界面
        try {
            Runtime.getRuntime().exec("adb shell input keyevent 4").waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch(InterruptedException ie){
            ie.printStackTrace();
        }


        //6、开启Stay awake
        //用while循环向上滑动直到屏幕出现Advanced元素
        System.out.println("6、开始设置：开启Stay awake");
        sfe = new SwipeFindElement(driver);
        sfe.swipeUpFindElement(By.xpath("//android.widget.TextView[@text='Advanced']"));
        driver.findElementByXPath(("//android.widget.TextView[@text='Advanced']")).click();//点击Advanced并进入


        //用while循环向上滑动直到屏幕出现Developer options元素
        sfe = new SwipeFindElement(driver);
        sfe.swipeUpFindElement(By.xpath("//android.widget.TextView[@text='Developer options']"));
        driver.findElementByXPath(("//android.widget.TextView[@text='Developer options']")).click();//点击Developer options并进入


        String Stay_awake_statue = driver.findElementByXPath("//android.widget.TextView[@text='Stay awake']/parent::android.widget.RelativeLayout/following-sibling::android.widget.LinearLayout/android.widget.Switch").getText();
        if(Stay_awake_statue.equals("OFF")){
            try {
                element  = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//android.widget.TextView[@text='Stay awake']/parent::android.widget.RelativeLayout/following-sibling::android.widget.LinearLayout/android.widget.Switch")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            element.click();
        }
        System.out.println("6、结束设置：开启Stay awake");
        System.out.println();



        //用while循环向上滑动直到屏幕出现Verify apps over USB元素
        System.out.println("7、开始设置：关闭Verify apps over USB");
        sfe = new SwipeFindElement(driver);
        sfe.swipeUpFindElement(By.xpath("//android.widget.TextView[@text='Verify apps over USB']"));

        String Verify_apps_over_USB_statue = driver.findElementByXPath("//android.widget.TextView[@text='Verify apps over USB']/parent::android.widget.RelativeLayout/following-sibling::android.widget.LinearLayout/android.widget.Switch").getText();
        if(Verify_apps_over_USB_statue.equals("ON")){
            try {
                element  = explicitwait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//android.widget.TextView[@text='Verify apps over USB']/parent::android.widget.RelativeLayout/following-sibling::android.widget.LinearLayout/android.widget.Switch")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            element.click();
        }
        System.out.println("7、结束设置：关闭Verify apps over USB");
        System.out.println();


        //按3次back键返回到settings界面
        try {
            process = Runtime.getRuntime().exec("adb shell input keyevent 4");
            process.waitFor();
            process = Runtime.getRuntime().exec("adb shell input keyevent 4");
            process.waitFor();
            process = Runtime.getRuntime().exec("adb shell input keyevent 4");
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        }catch(InterruptedException ie){
            ie.printStackTrace();
        }




        //2、执行adb命令开启蓝牙开关，命令：adb shell settings put global bluetooth_on 1
        String adb_open_bluetooth = "adb shell settings put global bluetooth_on 1";

        //3、设置 screen timeout 时间为30分钟,命令：adb shell settings put system screen_off_timeout 1800000
        String set_screen_timeout = "adb shell settings put system screen_off_timeout 1800000";

        /**
         * 4、通过adb 命令改变音量大小
         * adb shell media volume --show --stream 3 --set 1    把 Media volume 调至 1 ；
         * adb shell media volume --show --stream 0 --set 2    把 Call volume 调至 1 ；
         * adb shell media volume --show --stream 2 --set 1    把Ring volume 调至 1 ；
         * adb shell media volume --show --stream 4 --set 1    把Alarm volume 调至 1 ；
         */

        String media_volume = "adb shell media volume --show --stream 3 --set 1";
        String call_volume = "adb shell media volume --show --stream 0 --set 2";
        String ring_volume = "adb shell media volume --show --stream 2 --set 1";
        String alarm_volume = "adb shell media volume --show --stream 4 --set 1";

        //设置屏幕亮度11，命令：adb shell settings put system screen_brightness 11
        String screen_brightness = "adb shell settings put system screen_brightness 11";

        //设置默认美式英语，命令：adb shell settings put system system_locales en-US
        String system_locales = "adb shell settings put system system_locales en-US";

        System.out.println("8、开始设置：蓝牙为ON、锁屏时间为30分钟、各音量最小、屏幕亮度最低、默认美式英语");

        try {
            Runtime.getRuntime().exec(adb_open_bluetooth).waitFor();
            Runtime.getRuntime().exec(set_screen_timeout).waitFor();

            Runtime.getRuntime().exec(media_volume).waitFor();
            Runtime.getRuntime().exec(call_volume).waitFor();
            Runtime.getRuntime().exec(ring_volume).waitFor();
            Runtime.getRuntime().exec(alarm_volume).waitFor();

            Runtime.getRuntime().exec(screen_brightness).waitFor();
            Runtime.getRuntime().exec(system_locales).waitFor();

        } catch (IOException e) {
            e.printStackTrace();
        }catch(InterruptedException ie){
            ie.printStackTrace();
        }
        System.out.println("8、结束设置：蓝牙为ON、锁屏时间为30分钟、各音量最小、屏幕亮度最低、默认美式英语");
        System.out.println();

        System.out.println("9、退出appium driver。");
        System.out.println();
        driver.quit();

        //所有设置完成,卸载io.appium.settings，重启手机，设置生效
        System.out.println("10、所有设置完成,卸载io.appium.settings，重启手机，设置生效");
        try {
            Runtime.getRuntime().exec("adb uninstall io.appium.settings").waitFor();
            Runtime.getRuntime().exec("adb shell reboot").waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        }catch(InterruptedException ie){
            ie.printStackTrace();
        }
        System.out.println();
        System.out.println("#########10.0系统，GMS测试,手机端设置环境结束###########");
        System.out.println();
        System.out.println("请连接下一台手机，设置下一台手机环境。");


        }
    }

